<template>
    <div class="dashboard-container">
        <!-- 欢迎信息 -->
        <div class="welcome-section">
            <h1>欢迎使用场地预约管理系统</h1>
            <p>今天是 {{ currentDate }}，{{ greeting }}</p>
        </div>

        <!-- 数据概览卡片 -->
        <div class="stat-cards">
            <el-row :gutter="20">
                <el-col :span="6" v-for="(item, index) in statCards" :key="index">
                    <el-card shadow="hover" class="stat-card" :class="item.type">
                        <div class="card-content">
                            <el-icon class="card-icon">
                                <component :is="item.icon" />
                            </el-icon>
                            <div class="card-info">
                                <div class="card-value">{{ item.value }}</div>
                                <div class="card-label">{{ item.label }}</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!-- 图表区域 -->
        <div class="chart-section">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-card shadow="hover" class="chart-card">
                        <template #header>
                            <div class="chart-header">
                                <span>预约趋势</span>
                                <el-radio-group v-model="trendTimeRange" size="small">
                                    <el-radio-button value="week">本周</el-radio-button>
                                    <el-radio-button value="month">本月</el-radio-button>
                                </el-radio-group>
                            </div>
                        </template>
                        <div class="chart-container" ref="reservationTrendChart"></div>
                    </el-card>
                </el-col>
                <!--  -->
            </el-row>
        </div>

        <!-- 最近维护记录 -->
        <el-card shadow="hover" class="recent-section">
            <template #header>
                <div class="section-header">
                    <span>最近维护记录</span>
                    <el-button link @click="goToMaintain">查看全部</el-button>
                </div>
            </template>
            <el-table :data="recentMaintenance" style="width: 100%" :max-height="250">
                <el-table-column prop="venue_name" label="场地名称" width="150"></el-table-column>
                <el-table-column prop="start_time" label="开始时间" width="180"></el-table-column>
                <el-table-column prop="end_time" label="结束时间" width="180"></el-table-column>
                <el-table-column prop="reason" label="原因"></el-table-column>
            </el-table>
        </el-card>

        <!-- 今日预约 -->
        <el-card shadow="hover" class="recent-section">
            <template #header>
                <div class="section-header">
                    <span>今日预约</span>
                </div>
            </template>
            <el-table :data="todayReservations" style="width: 100%" :max-height="250">
                <el-table-column prop="venue_name" label="场地名称" width="150"></el-table-column>
                <el-table-column prop="no" label="预约学号/工号" width="150"></el-table-column>
                <el-table-column prop="start_time" label="开始时间" width="180"></el-table-column>
                <el-table-column prop="end_time" label="结束时间" width="180"></el-table-column>
                <el-table-column prop="status" label="状态">
                    <template #default="scope">
                        <el-tag :type="scope.row.status">{{ scope.row.status }}</el-tag>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import { apiFindReservation, apiGetReservationCountsByWeek } from '@/request/reservation'
import { apiFindMaintenance } from '@/request/maintenance'
import { apiGetVenueInfoById } from '@/request/venue'

const router = useRouter()

// 当前日期和问候语
const currentDate = computed(() => dayjs().format('YYYY年MM月DD日'))
const greeting = computed(() => {
    const hour = dayjs().hour()
    if (hour < 12) return '早上好'
    if (hour < 18) return '下午好'
    return '晚上好'
})

// 统计卡片数据
const statCards = reactive([
    { label: '维护中场地', value: '0', icon: 'Tools', type: 'danger' },
    { label: '今日预约', value: '0', icon: 'Calendar', type: 'warning' },
])

// 图表相关
const reservationTrendChart = ref(null)
const trendTimeRange = ref('week')

// 最近维护记录
const recentMaintenance = ref([])

// 今日预约
const todayReservations = ref([])


// 跳转到维护页面
const goToMaintain = () => {
    router.push('/home/gymMaintain')
}

const countByWeek = ref([0, 0, 0, 0, 0, 0, 0])
// 初始化图表
const initCharts = () => {
    // 预约趋势图
    const trendChart = echarts.init(reservationTrendChart.value)
    const trendOption = {
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            data: ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '预约数量',
                type: 'line',
                smooth: true,
                data: countByWeek.value,
                itemStyle: {
                    color: '#409EFF'
                },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
                            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
                        ]
                    }
                }
            }
        ]
    }
    trendChart.setOption(trendOption)

    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', () => {
        trendChart.resize()
    })
}

// 预约状态
const Reservation = {
    Unpaid: 0, //未支付
    Paid: 1, //已支付
    Reserved: 2,// 已预约
    Canceled: 3,// 已取消
    CheckedIn: 4,// 已核销
    Expired: 5,// 已过期
};

// 获取状态对应的标签类型
const getStatusType = (status) => {
    const types = []
    types[Reservation.Expired] = 'info'
    types[Reservation.CheckedIn] = 'success'
    types[Reservation.Reserved] = 'primary'
    types[Reservation.Canceled] = 'warning'
    return types[status]
}

// 获取预约记录
const FindReservation = async () => {
    const res = await apiFindReservation({
        page: 1,
        pageSize: 100,
        start_time: dayjs().format('YYYY-MM-DD'),
        end_time: dayjs().add(1, "day").format('YYY Y-MM-DD'),
        status: -1
    })

    todayReservations.value = res.data.reservations || [];
    statCards[1].value = res.data.total || 0;

    todayReservations.value.forEach((rez) => {
        // console.log(rez);
        rez.start_time = dayjs(rez.start_time).format('HH:mm');
        rez.end_time = dayjs(rez.end_time).format('HH:mm');
        apiGetVenueInfoById(rez.venue_id).then((res) => {
            rez.venue_name = `${res.data.name}-第${res.data.number}场地`;
        })
        rez.status = getStatusType(rez.status)
    });
    todayReservations.value.reverse();
}

// 获取维护记录
const fetchMaintenances = async () => {
    try {
        const data = {
            start_time: dayjs().format('YYYY-MM-DD'),
            end_time: dayjs().add(1, "day").format('YYYY-MM-DD'),
            page: 1,
            page_size: 100
        }

        if (data.start_time) {
            data.start_time = dayjs(data.start_time).format('YYYY-MM-DD')
        }
        if (data.end_time) {
            data.end_time = dayjs(data.end_time).format('YYYY-MM-DD')
        }

        // const res = await apiFindMaintenance(data)
        // res.data.maintenances.forEach(maintenance => {
        //     maintenance.start_time = dayjs(maintenance.start_time).format('HH:mm')
        //     maintenance.end_time = dayjs(maintenance.end_time).format('HH:mm')
        //     apiGetVenueInfoById(maintenance.venue_id).then((res) => {
        //         maintenance.venue_name = `${res.data.name}-第${res.data.number}场地`;
        //     })
        // })
        const res = await apiFindMaintenance(data)
        const maintenances = res.data.maintenances || [];
        
        // 使用 Promise.all 等待所有场地信息加载完成
        await Promise.all(maintenances.map(async (maintenance) => {
            maintenance.start_time = dayjs(maintenance.start_time).format('HH:mm');
            maintenance.end_time = dayjs(maintenance.end_time).format('HH:mm');
            try {
                const venueRes = await apiGetVenueInfoById(maintenance.venue_id);
                maintenance.venue_name = `${venueRes.data.name}-第${venueRes.data.number}场地`;
            } catch (error) {
                console.error('获取场地信息失败:', error);
                maintenance.venue_name = '未知场地';
            }
        }));
        recentMaintenance.value = res.data.maintenances || []
        recentMaintenance.value.reverse()
        // console.log(recentMaintenance.value);
        
        statCards[0].value = res.data.total || 0;

    } catch (e) {
        recentMaintenance.value = []
        statCards[0].value = 0
    }
}

import { watch } from 'vue'

// 监听 trendTimeRange 的变化
watch(trendTimeRange, async (newValue) => {
    // console.log("newValue:", newValue);
    countByWeek.value=[0, 0, 0, 0, 0, 0, 0];
    
    await FindReservationCountsByWeek(newValue)
    updateChart()
})

// 获取通过week分组的预约记录
const FindReservationCountsByWeek = async (flag) => {
    const res = await apiGetReservationCountsByWeek({
        start_time: dayjs().startOf(flag).format('YYYY-MM-DD'),
        end_time: dayjs().endOf(flag).format('YYYY-MM-DD'),
    })
    Object.entries(res.data.counts).forEach(([weekday, count]) => {
        countByWeek.value[weekday] = count;
    });
}
const updateChart = () => {
    if (reservationTrendChart.value) {
        const chart = echarts.getInstanceByDom(reservationTrendChart.value);
        if (chart) {
            chart.setOption({
                series: [{
                    data: countByWeek.value
                }]
            });
        }
    }
}

onMounted(async () => {
    await FindReservation()
    await fetchMaintenances()
    await FindReservationCountsByWeek("week")

    initCharts()
})
</script>

<style scoped>
.dashboard-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 60px);
    width: 100%;
}

.welcome-section {
    margin-bottom: 24px;

    h1 {
        font-size: 24px;
        color: #303133;
        margin-bottom: 8px;
    }

    p {
        color: #606266;
        font-size: 14px;
    }
}

.stat-cards {
    margin-bottom: 24px;

    .stat-card {
        height: 100px;

        &.primary .card-icon {
            background-color: rgba(64, 158, 255, 0.1);
            color: #409EFF;
        }

        &.success .card-icon {
            background-color: rgba(103, 194, 58, 0.1);
            color: #67C23A;
        }

        &.warning .card-icon {
            background-color: rgba(230, 162, 60, 0.1);
            color: #E6A23C;
        }

        &.danger .card-icon {
            background-color: rgba(245, 108, 108, 0.1);
            color: #F56C6C;
        }

        .card-content {
            display: flex;
            align-items: center;
            height: 100%;
        }

        .card-icon {
            width: 48px;
            height: 48px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            margin-right: 16px;
        }

        .card-info {
            flex: 1;
        }

        .card-value {
            font-size: 24px;
            font-weight: bold;
            line-height: 1.2;
            color: #303133;
        }

        .card-label {
            font-size: 14px;
            color: #909399;
            margin-top: 4px;
        }
    }
}

.chart-section {
    margin-bottom: 24px;

    .chart-card {
        margin-bottom: 20px;
    }

    .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .chart-container {
        height: 350px;
    }
}

.recent-section {
    margin-bottom: 24px;

    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
}
</style>
